package com.ruoyi.web.service.impl;

import java.util.Collections;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.kubernetes.models.CSRRequestData;
import com.ruoyi.kubernetes.models.CSRResponseData;
import com.ruoyi.kubernetes.models.RoleBindingRequestData;
import com.ruoyi.kubernetes.service.IKubernetesClientRoleBindingService;
import com.ruoyi.kubernetes.service.IKubernetesClientUserService;
import com.ruoyi.web.domain.config.KubernetesConfig;
import com.ruoyi.web.domain.config.KubernetesConfigCluster;
import com.ruoyi.web.domain.config.KubernetesConfigContext;
import com.ruoyi.web.domain.config.KubernetesConfigUser;
import com.ruoyi.web.mapper.KubernetesUserRoleBindingMapper;
import com.ruoyi.web.utils.KubernetesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.web.domain.KubernetesUserRoleBinding;
import com.ruoyi.web.mapper.KubernetesUserMapper;
import com.ruoyi.web.domain.KubernetesUser;
import com.ruoyi.web.service.IKubernetesUserService;

/**
 * K8s用户Service业务层处理
 *
 * @author xuchengchao
 * @date 2022-04-17
 */
@Service
public class KubernetesUserServiceImpl implements IKubernetesUserService {
    @Autowired
    private KubernetesUserMapper kubernetesUserMapper;

    @Autowired
    private KubernetesUserRoleBindingMapper kubernetesUserRoleBindingMapper;

    @Autowired
    private IKubernetesClientRoleBindingService kubernetesClientRoleBindingService;

    @Autowired
    private IKubernetesClientUserService iKubernetesClientUserService;

    /**
     * 查询K8s用户
     *
     * @param id K8s用户主键
     * @return K8s用户
     */
    @Override
    public KubernetesUser selectKubernetesUserById(Long id) {
        return kubernetesUserMapper.selectKubernetesUserById(id);
    }

    /**
     * 查询K8s用户列表
     *
     * @param kubernetesUser K8s用户
     * @return K8s用户
     */
    @Override
    public List<KubernetesUser> selectKubernetesUserList(KubernetesUser kubernetesUser) {
        return kubernetesUserMapper.selectKubernetesUserList(kubernetesUser);
    }

    /**
     * 新增K8s用户
     *
     * @param kubernetesUser K8s用户
     * @return 结果
     */
    @Transactional
    @Override
    public int insertKubernetesUser(KubernetesUser kubernetesUser) {
        kubernetesUser.setCreateTime(DateUtils.getNowDate());
        CSRRequestData csrRequestData = new CSRRequestData();
        csrRequestData.setUsername(kubernetesUser.getUsername());
        csrRequestData.setGroup(kubernetesUser.getGroupName());
        csrRequestData.setExpirationDays(kubernetesUser.getExpirationDays().intValue());
        CSRResponseData csrResponseData = iKubernetesClientUserService.createUser(csrRequestData);
        if (!csrResponseData.isSuccess()) {
            return 0;
        }
        kubernetesUser.setCrtKey(csrResponseData.getClient_crt());
        kubernetesUser.setPublicKey(csrResponseData.getClient_publicKey());
        kubernetesUser.setPrivateKey(csrResponseData.getClient_privateKey());
        int rows = kubernetesUserMapper.insertKubernetesUser(kubernetesUser);
        insertKubernetesUserRoleBinding(kubernetesUser);
        return rows;
    }

    /**
     * 修改K8s用户
     *
     * @param kubernetesUser K8s用户
     * @return 结果
     */
    @Transactional
    @Override
    public int updateKubernetesUser(KubernetesUser kubernetesUser) {
        kubernetesUserMapper.deleteKubernetesUserRoleBindingByUserId(kubernetesUser.getId());
        insertKubernetesUserRoleBinding(kubernetesUser);
        return kubernetesUserMapper.updateKubernetesUser(kubernetesUser);
    }

    /**
     * 批量删除K8s用户
     *
     * @param ids 需要删除的K8s用户主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteKubernetesUserByIds(Long[] ids) {
        if (ids.length==1){
            List<KubernetesUserRoleBinding> kubernetesUserRoleBindingList = kubernetesUserRoleBindingMapper.selectKubernetesUserRoleBindingListByUserId(ids[0]);
            List<RoleBindingRequestData> roleBindingRequestDataList = new ArrayList();
            kubernetesUserRoleBindingList.forEach(o -> {
                roleBindingRequestDataList.add(KubernetesUtils.getRoleBindingRequestData(o));
            });
            if (kubernetesClientRoleBindingService.deleteBindings(roleBindingRequestDataList)) {
                kubernetesUserMapper.deleteKubernetesUserRoleBindingByUserId(ids[0]);
                return kubernetesUserMapper.deleteKubernetesUserById(ids[0]);
            }else {
                return 0;
            }
        }
        kubernetesUserMapper.deleteKubernetesUserRoleBindingByUserIds(ids);
        return kubernetesUserMapper.deleteKubernetesUserByIds(ids);
    }

    /**
     * 删除K8s用户信息
     *
     * @param id K8s用户主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteKubernetesUserById(Long id) {
        List<KubernetesUserRoleBinding> kubernetesUserRoleBindingList = kubernetesUserRoleBindingMapper.selectKubernetesUserRoleBindingListByUserId(id);
        List<RoleBindingRequestData> roleBindingRequestDataList = new ArrayList();
        kubernetesUserRoleBindingList.forEach(o -> {
            roleBindingRequestDataList.add(KubernetesUtils.getRoleBindingRequestData(o));
        });
        if (kubernetesClientRoleBindingService.deleteBindings(roleBindingRequestDataList)) {
            kubernetesUserMapper.deleteKubernetesUserRoleBindingByUserId(id);
            return kubernetesUserMapper.deleteKubernetesUserById(id);
        } else {
            return 0;
        }
    }

    @Override
    public KubernetesConfig getKubernetesConfig(Long id) {
        KubernetesConfig kubernetesConfig = new KubernetesConfig();
        KubernetesUser kubernetesUser = kubernetesUserMapper.selectKubernetesUserById(id);
        // cluster
        KubernetesConfigCluster kubernetesConfigCluster = new KubernetesConfigCluster();
        JSONObject clusterObject = new JSONObject();
        clusterObject.put("server", kubernetesUser.getServerUrl());
        clusterObject.put("insecure-skip-tls-verify", true);
        kubernetesConfigCluster.setCluster(clusterObject);
        kubernetesConfig.getClusters().add(kubernetesConfigCluster);
        //context
        KubernetesConfigContext kubernetesConfigContext = new KubernetesConfigContext();
        JSONObject contextObject = new JSONObject();
        contextObject.put("cluster", "externalCluster");
        contextObject.put("user", kubernetesUser.getUsername());
        kubernetesConfigContext.setContext(contextObject);
        kubernetesConfig.getContexts().add(kubernetesConfigContext);
        //user
        KubernetesConfigUser kubernetesConfigUser = new KubernetesConfigUser();
        kubernetesConfigUser.setName(kubernetesUser.getUsername());
        JSONObject userObject = new JSONObject();
        userObject.put("client-certificate-data", kubernetesUser.getCrtKey());
        userObject.put("client-key-data", kubernetesUser.getPrivateKey());
        kubernetesConfigUser.setUser(userObject);
        kubernetesConfig.getUsers().add(kubernetesConfigUser);
        return kubernetesConfig;
    }

    /**
     * 新增K8s用户权限信息
     *
     * @param kubernetesUser K8s用户对象
     */
    public void insertKubernetesUserRoleBinding(KubernetesUser kubernetesUser) {
        List<KubernetesUserRoleBinding> kubernetesUserRoleBindingList = kubernetesUser.getKubernetesUserRoleBindingList();
        Long id = kubernetesUser.getId();
        if (StringUtils.isNotNull(kubernetesUserRoleBindingList)) {
            List<KubernetesUserRoleBinding> list = new ArrayList<KubernetesUserRoleBinding>();
            for (KubernetesUserRoleBinding kubernetesUserRoleBinding : kubernetesUserRoleBindingList) {
                kubernetesUserRoleBinding.setUserId(id);
                list.add(kubernetesUserRoleBinding);
            }
            if (list.size() > 0) {
                kubernetesUserMapper.batchKubernetesUserRoleBinding(list);
            }
        }
    }
}
